import socket
import requests
import json
from threading import Thread

# 封装获取token的函数
def get_token():
    login_url = 'http://localhost:6868/login'
    login_data = {
        "id": "0",
        "password": "YunShi2024YunShi"
    }
    try:
        login_response = requests.post(login_url, json=login_data)
        if login_response.status_code == 200:
            try:
                login_json = login_response.json()
                return login_json.get('token')
            except json.JSONDecodeError:
                print('登录响应不是有效的JSON格式')
                return None
        else:
            print('登录失败，状态码:', login_response.status_code)
            return None
    except requests.RequestException as e:
        print('登录请求发生异常:', e)
        return None


# 封装转发请求的函数，根据target修改请求头部
def forward_request(token, target, data):
    url = 'http://localhost:6868' + target
    headers = {}
    if target == '/employee/facialAttendance':
        headers['Content-Type'] = f'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
    else:
        headers['Authorization'] = token
    try:
        # 使用requests.Request构建请求对象，以便设置自定义头部
        req = requests.Request('POST', url, data=data, headers=headers)
        if target == '/employee/getTime':
            req = requests.Request('GET', url)
        prepped = req.prepare()
        session = requests.Session()
        response = session.send(prepped)
        return response.text
    except requests.RequestException as e:
        print('转发请求发生异常:', e)
        return None


# 创建一个TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定服务器地址和端口
server_address = ('0.0.0.0', 12345)
server_socket.bind(server_address)

# 监听连接，最大连接数为10
server_socket.listen(10)
print('服务器正在监听 {}:{}'.format(*server_address))


def handle_client(client_socket):
    try:
        # 接收客户端发送的数据
        data = client_socket.recv(819200)
        message = data
        #print('接收到客户端发送的数据:', message.decode('utf-8'))
        if data:
            try:
                token = get_token()

                parts = data.split(b'\n', 1)
                target = parts[0].decode('utf-8').strip()  # 将 target 部分从字节解码为文本
                print('目标路径:', target)

                data = parts[1]  # data 部分保持为字节数据

                response_text = forward_request(token, target, data)
                if response_text:
                    print('服务器返回的数据:', response_text)
                    client_socket.send(response_text.encode())
            except UnicodeDecodeError:
                print('数据解码失败，可能是编码格式不正确')
        else:
            print('客户端已断开连接')
    finally:
        # 关闭客户端套接字
        client_socket.close()


# 创建一个 TCP 套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定服务器地址和端口
server_address = ('0.0.0.0', 12345)
server_socket.bind(server_address)

# 监听连接，最大连接数为 10
server_socket.listen(10)
print('服务器正在监听 {}:{}'.format(*server_address))


while True:
    try:
        # 接受客户端连接
        client_socket, client_address = server_socket.accept()
        print('接受来自 {}:{} 的连接'.format(client_address[0], client_address[1]))

        # 创建一个新线程来处理客户端连接
        client_thread = Thread(target=handle_client, args=(client_socket,))
        client_thread.start()
    except KeyboardInterrupt:
        print('程序被用户中断，正在退出...')
        break
